<template>
	<view class="view-fiex">
		<supplier-navbar :title="detail.store_name" ></supplier-navbar>
		<!-- 头部内容 -->
		<!-- <product-top /> -->
		<!-- 列表 -->
		<view class="flex-1 ovh">
			<mo-product-list open-tag :tagKey="tagKey" :list="list" @scrollEnd="scrollEnd">
				<template v-slot:header="{item}">
					<view class="title">{{item.name}}</view>
				</template>
				<template v-slot="{item}">
					<product-item v-for="(child, childIndex) in item.list" :key="childIndex" :item="child"
						:categoryItem="item" @onChange="onChange"></product-item>
				</template>
			</mo-product-list>
		</view>
		<!-- 底部按钮 -->
		<product-bottom :list="cartList" @buyNow="buy">
			<template v-slot:header="{list}">
				<!-- <view class="tp-tips">折扣已减2000</view> -->
				<view class="tp-info">
					<view class="">商品</view>
					<view class="" @click="clearCart">清空购物车</view>
				</view>
			</template>
			<template v-slot:popItem="{item}">
				<goodsCart v-for="(child, childIndex) in item.list" :key="childIndex" :item="child" :categoryItem="item"
					@onChange1="onChange1"></goodsCart>
			</template>
		</product-bottom>
		<!-- 规格弹框 -->
		<u-popup mode="bottom" ref="popup">
			<goods-detail-skuPop :attrList="attrList" :checkedSkuId="checkedSkuId" @checkedIds="checkedIds" @addToCart="addToCart" :details="details"
				:specInfo="specInfo"></goods-detail-skuPop>
		</u-popup>
	</view>
</template>

<script>
	import moProductList from "./mo-product-list.vue";
	// import productTop from './component/product-top.vue'
	import productItem from './component/product-item.vue'
	import goodsCart from './component/goods-cart.vue'
	import productBottom from './component/product-bottom.vue'
	import goodsDetailSkuPop from './component/goods-detail-skuPop.vue'
	import testJson from './test.json'
	import {
		mapState,
		mapMutations,
		mapActions
	} from "vuex";
	import {
		SupplierCenterApi,
		GoodsCenterApi
	} from '@/api/serves.js'
	export default {
		components: {
			moProductList,
			// productTop,
			productItem,
			goodsDetailSkuPop,
			productBottom,
			goodsCart
		},
		data() {
			return {
				list: [],
				tagKey: 'tag',
				merch_id: null,
				detail: {},
				attrList: [], // 商品规格分类展示
				skuList: [], // 商品规格组合
				checkedSkuId: '', // 已选的规格skuid
				specInfo: {}, // 选中规格信息
				itemId: '', // 商品id
				details: {}, // 商品详情数据
			}
		},
		computed: {
			...mapState('user', ['userCarts1', 'cartList1','userCarts']),
			cartList() {
				console.log('this.list',this.list);
				// console.log('this.cartList',this.cartList1);
				const ls = JSON.parse(JSON.stringify(this.list))
				console.log('ls', ls);
				let list = ls.reduce((t, item) => {
					const child = item.list.filter(el => {
						return !!el.selected
					})
					if (child.length) {
						t.push({
							...item,
							list: child
						})
					}
					return t
				}, [])
				list.forEach(item => item.list = [])
				if (list.length) list[0].list = this.cartList1
				return list
			},
			allTag() {
				return this.cartList.reduce((t, c) => {
					if (c[this.tagKey]) {
						t = t + c[this.tagKey]
					}
					console.log('t',t);
					return t
				}, 0)
			}
		},
		watch: {
			userCarts1: {
				handler(val) {
					// console.log('111',val);
					this.list.forEach((item, index) => {
						item.list.forEach((item1, index1) => {
							this.$set(this.list[index].list[index1], 'selected', 0)
						})
						item.tag = 0
					})
					let data = val.filter(item => item.id == this.merch_id)
					if (!!data.length) {
						// 累加相同goods_id商品的total_num , 得到不同规格但商品id一致的总数
						let result = data[0].goods_list.reduce((prev, cur) => {
							if (prev.length === 0) prev.push({}) // 推个空对象，防止不遍历数组
							let index = prev.findIndex(item => item.goods_id === cur.goods_id)
							console.log('index', index);

							if (index === -1) { // 没有相同id
								cur.selected = cur.total_num * 1
								prev.push(cur)
							} else { //有相同id
								prev[index].selected += cur.total_num * 1
							}
							return prev
						}, [])
						result.shift() // 删除第一个空对象
						console.log('result', result);

						console.log('data[0].goods_list', data[0].goods_list);
						result.forEach(item => {
							let categoryIndex = this.list.findIndex(item1 => item1.id == item.merch_category_id)
							let goodsIndex = this.list[categoryIndex].list.findIndex(item1 => item1.id == item
								.goods_id)
							this.$set(this.list[categoryIndex].list[goodsIndex], 'selected', item.selected)
						})

						this.list.forEach(item => {
							let tag = item.list.reduce((t, c) => {
								if (c.selected) {
									t = t + c.selected
								}
								return t
							}, 0)
							item.tag = tag
						})
						console.log('this.list111',this.list);
					}
				},
				deep: true
			},
			attrList: {
				handler(newVal, oldVal) {
					console.log('attrList', newVal);
					if (!this.skuList.length) return
					let info = []
					for (let item of this.attrList) {
						if (!item.checkedId) break
						info.push(item.checkedId)
					}
					if (info.length == this.attrList.length) {
						this.checkedSkuId = info.join('_')
						for (let v of this.skuList) {
							if (v.spec_sku_id == this.checkedSkuId) {
								this.specInfo = v.form
							}
						}
					}
					console.log('this.checkedSkuId', this.checkedSkuId);
					console.log('this.specInfo', this.specInfo);
				},
				deep: true,
				immediate: true
			},
		},
		onLoad(options) {
			this.merch_id = options.id
			this.initData()
		},
		onShow() {
			console.log(666,{
				goods_type: this.detail.type === 1 ? 1 : 5,
				merch_id: this.merch_id
			});
			this.$store.dispatch('user/getUserCartsInfo', {
				goods_type: this.detail.type === 1 ? 1 : 5,
				merch_id: this.merch_id,
				isGetAll: true,
			})
		},
		methods: {
			async initData() {
				this.getCategoryGoodsList()
				this.getMerchDetail()
			},
			getMerchDetail() {
				SupplierCenterApi.merchDetail({
					id: this.merch_id
				}).then(res => {
					console.log('获取商户详情', res);
					if (res.code == 1) {
						this.detail = res.data.data
						this.$store.dispatch('user/getUserCartsInfo', {
							goods_type: this.detail.type === 1 ? 1 : 5,
							merch_id: this.merch_id,
							isGetAll: true,
						})
						setTimeout(()=>{
							console.log('this.userCarts',this.userCarts);
						},2000)
					}
				})
			},
			getCategoryGoodsList() {
				uni.showLoading()
				SupplierCenterApi.categoryGoodsList({
					merch_id: this.merch_id
				}).then(res => {
					console.log('获取商户商品列表', res.data.data);
					uni.hideLoading()
					if (res.code == 1) {
						this.list = res.data.data
						// 	console.log(444,this.list);
					}
				})
			},
			tabbarChange(e) {
				if (e == this.current) return
				uni.redirectTo({
					url: this.list[e].pagePath
				})
			},
			scrollEnd(e) {
				console.log(e)
			},
			async onChange(item) {
				// console.log(item);
				this.checkedSkuId = ''
				this.itemId = item.item.id
				this._goodsdetail(item)
			},
			// 购物车商品数量加 1
			onChange1(item) {
				console.log('当前商品信息', item);
				let {
					goods_id,
					goods_sku_id,
					total_num
				} = item.item
				let params = {
					goods_id,
					goods_sku_id,
					goods_num: 1
				}
				if (item.type == 'add') {
					GoodsCenterApi.addCart(params).then(res => {
						if (res.code == 1) {
							uni.showToast({
								title: '加入成功'
							})
							this.$store.dispatch('user/getUserCartsInfo', {
								goods_type: this.detail.type === 1 ? 1 : 5,
								merch_id: this.merch_id,
								isGetAll:true
							})
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					})
				} else {
					if (total_num > 1) {
						GoodsCenterApi.subCart(params).then(res => {
							if (res.code == 1) {
								this.$store.dispatch('user/getUserCartsInfo', {
									goods_type: this.detail.type === 1 ? 1 : 5,
									merch_id: this.merch_id,
									isGetAll:true
								})
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}
						})
					} else {
						this.deleteCart({
							goods_id,
							goods_sku_id
						})
						this.$store.dispatch('user/getUserCartsInfo', {
							goods_type: this.detail.type === 1 ? 1 : 5,
							merch_id: this.merch_id,
							isGetAll:true
						})
					}
				}

			},
			updateSelect({
				id,
				item
			}) {
				return new Promise((resole, reject) => {
					this.$nextTick(function() {
						this.list.forEach((el, index) => {
							if (el.id == id) {
								el.list.forEach((e, i) => {
									if (e.id == item.id) {
										const obj = {
											...e,
											...item
										}
										this.$set(el.list, i, obj)
									}
								})
								this.$set(this.list, index, {
									...el
								})
							}
						})
						resole()
					})
				})
			},
			async clearCart() {
				let goodsIdList = []  // 商品id列表
				let goodsSkuId = []  // 商品规格列表
				console.log('this.userCarts1',this.userCarts1);
				this.userCarts1[0].goods_list.forEach((el, index) => {
					goodsIdList.push(el.goods_id)
					goodsSkuId.push(el.goods_sku_id)
				})
				await this.deleteCart({
					goods_id: goodsIdList.join(","),
					goods_sku_id: goodsSkuId.join(",")
				})
				this.$store.dispatch('user/getUserCartsInfo', {
					goods_type: this.detail.type === 1 ? 1 : 5,
					merch_id: this.merch_id,
					isGetAll:true
				})
			},
			// 获取商品详情
			_goodsdetail(item) {
				// this.checkedSkuId = ''
				this.attrList = []
				GoodsCenterApi.goodsdetail({
					goods_id: this.itemId
				}).then(res => {
					console.log('获取商品详情', res);
					if (res.code == 1) {
						let result = res.data
						this.details = result.detail
						if (result.specData) {
							this.specInfo = result.specData.spec_list[0].form
							let list = result.specData.spec_attr
							// list.map(item=> {
							// 	item.checkedId = ''
							// })
							// console.log('list',list);
							this.attrList = list
							this.skuList = result.specData.spec_list
						} else {
							this.checkedSkuId = this.details.spec[0].spec_sku_id
							console.log('this.checkedSkuId', this.checkedSkuId);
							this.specInfo = this.details.spec[0]
							// this.specInfo.imgshow= this.details.image
						}
						this.specInfo.imgshow = this.details.image
						if (item.type == 'add') {
							this.$refs.popup.open()
						} else if (item.type == 'cut') {
							this.subCart()
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			// 选中规格
			checkedIds(e) {
				this.checkedSkuId = e.item_id + ""
				this.specInfo = this.details.spec.filter(item=>item.spec_sku_id == e.item_id)[0]
				// 防止多规格商品没有上传规格图片
				if(this.specInfo.spec_image){ 
					this.specInfo.imgshow = this.$_BASE_IMG_API + this.specInfo.spec_image
				}else{
					this.specInfo.imgshow = this.details.image
				}
				
			},
			// 加入购物车
			addToCart(buyNum) {
				if (!this.isLogin) return this._login()
				// console.log(this.attrList);
				for (let item of this.attrList) {
					// console.log(item);
					if (!this.checkedSkuId) return uni.showToast({
						title: `请选择${item.group_name}`,
						icon: 'none'
					})
				}
				let params = {
					goods_num: buyNum,
					goods_id: this.itemId,
					goods_sku_id: this.checkedSkuId
				}
				console.log('params', params);
				GoodsCenterApi.addCart(params).then(res => {
					this.$refs.popup.close()
					if (res.code == 1) {
						uni.showToast({
							title: '加入成功'
						})
						this.$store.dispatch('user/getUserCartsInfo', {
							goods_type: this.detail.type === 1 ? 1 : 5,
							merch_id: this.merch_id,
							isGetAll: true,
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			// 购物车商品减1
			subCart() {
				if (!this.isLogin) return this._login()
				let params = {
					goods_num: 1,
					goods_id: this.itemId,
					goods_sku_id: this.checkedSkuId
				}
				let goodsTotalNum = this.userCarts1.find(item => item.id == this.merch_id).goods_list.find(item => item
					.goods_id == this.itemId).total_num
				if (goodsTotalNum > 1) {
					GoodsCenterApi.subCart(params).then(res => {
						this.$refs.popup.close()
						if (res.code == 1) {
							this.$store.dispatch('user/getUserCartsInfo', {
								goods_type: this.detail.type === 1 ? 1 : 5,
								merch_id: this.merch_id
							})
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					})
				} else {
					this.deleteCart({
						goods_id: this.itemId,
						goods_sku_id: this.checkedSkuId
					})
				}
			},
			// 购物车删除
			deleteCart(params) {
				if (!this.isLogin) return this._login()
				// let params = {
				//   goods_type: 5,
				//   goods_id: this.itemId,
				//   goods_sku_id: this.checkedSkuId
				// }
				GoodsCenterApi.deleteCart({
					...params,
					goods_type: this.detail.type === 1 ? 1 : 5
				}).then(res => {
					if (res.code == 1) {
						this.$store.dispatch('user/getUserCartsInfo', {
							goods_type: this.detail.type === 1 ? 1 : 5,
							merch_id: this.merch_id
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			buy(type) {
				if (!this.userCarts1.length) return this.$u.toast('购物车暂无商品', 2000)
				if (!this.allTag) return this.$Toast('选择结算的商品')
				let list = []
				// console.log(this.userCarts1,111111111111);
				for (let shopCart of this.userCarts1) {
					let obj = {
						merch_id: '',
						goods_id: '',
						goods_sku_id: ''
					}
					let goods_id_list = [] // 商品id列表
					let goods_sku_id_list = []

					for (let item of shopCart.goods_list) {
						if (!obj.merch_id) obj.merch_id = shopCart.id //商户id
						goods_id_list.push(item.goods_id)
						goods_sku_id_list.push(item.goods_sku_id)
					}
					obj.goods_id = goods_id_list.join(',')
					obj.goods_sku_id = goods_sku_id_list.join(',')
					obj.merch_id = this.merch_id
					if (goods_id_list.length) list.push(obj)
				}
				// let params = [{
				// 		goods_id: this.itemId,
				// 		goods_num: buyNum,
				// 		goods_sku_id: this.checkedSkuId,
				// 		merch_id:this.details.merch_id,
				// 		is_special: this.details.is_special
				// 	}]
				uni.navigateTo({
					url: `/pages/supplierPage/supplierGoodsOrderAdd/supplierGoodsOrderAdd?type=common&orderInfo=${JSON.stringify(list)}&goodsType=${this.detail.type === 1 ? 1 : 5}`,
					fail: (err) => {
						console.log(err, "跳转登录回调");
					}
				})

			}
		}
	}
</script>

<style lang="scss" scoped>
	@import './base.scss';

	page {
		background: #f8f8f8;
	}

	.view-fiex {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: calc(100vh - constant(safe-area-inset-bottom));
		height: calc(100vh - env(safe-area-inset-bottom));
		/* #ifndef MP-WEIXIN */
		height: calc(100vh - 44px - constant(safe-area-inset-bottom));
		height: calc(100vh - 44px - env(safe-area-inset-bottom));
		/*  #endif  */
	}

	.flex-1 {
		flex: 1;
	}

	.ovh {
		overflow: hidden;
	}

	.title {
		padding: 30rpx;
	}

	.innor {
		margin-left: 20rpx;
		margin-right: 20rpx;
	}

	.tp-tips {
		text-align: center;
		background-color: #f9ede3;
		font-size: 24rpx;
		padding: 12rpx 0;
	}

	.tp-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding: 15rpx 30rpx;
		font-size: 28rpx;
		color: gray;
	}
</style>